package com.zbkj.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.zbkj.admin.model.order.Order;
import com.zbkj.admin.model.user.User;
import com.zbkj.admin.pojo.EbUserRelationshipEntity;
import com.zbkj.admin.pojo.EbUserVoucherRecordEntity;
import com.zbkj.admin.service.*;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.result.R;
import org.springframework.web.bind.annotation.*;
import com.zbkj.admin.pojo.EbUserIntegralProductRecordEntity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 用户商品所获积分记录表 控制层。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@RestController
@RequiredArgsConstructor
@RequestMapping({"/api/admin/ebUserIntegralProductRecord", "/api/front/ebUserIntegralProductRecord"})
public class EbUserIntegralProductRecordController {

    private final UserService userService;
    private final OrderService orderService;
    private final EbUserVoucherRecordService userVoucherRecordService;
    private final IEbUserIntegralProductRecordService ebUserIntegralProductRecordService;
    private final EbUserIntegralGoldCoinRecordService goldCoinRecordService;
    private final EbUserRelationshipService userRelationshipService;

    @GetMapping("/countOrder")
    public R<Dict> countOrder() {
        User info = userService.getInfo();
        LocalDateTime date = LocalDateTime.now();

        long todayCount = orderService.count(Wrappers.<Order>lambdaQuery()
//                .ge(Order::getCreateTime, DateUtil.beginOfDay(DateUtil.date(date)))
//                .le(Order::getCreateTime, date)
                        .eq(Order::getUid, info.getId())
                        .eq(Order::getIsUserDel, false).eq(Order::getIsMerchantDel, false)
                        .in(Order::getStatus, 1, 5, 4, 6).eq(Order::getIsDel, false)
        );

        QueryWrapper queryWrapper = userRelationshipService.from()
                .where(EbUserRelationshipEntity::getPId).eq(info.getId());
        List<EbUserRelationshipEntity> listed = userRelationshipService.list(queryWrapper);
        long toDayFansCount = 0L;
        if (CollUtil.isNotEmpty(listed)) {
            toDayFansCount = orderService.count(Wrappers.<Order>lambdaQuery()
                    .ge(Order::getCreateTime, DateUtil.beginOfDay(DateUtil.date(date)))
                    .le(Order::getCreateTime, date)
                    .in(Order::getUid, listed.stream().map(EbUserRelationshipEntity::getUid).toList())
                    .in(Order::getStatus, 1, 5, 4, 6).eq(Order::getIsDel, false)
                    .eq(Order::getIsUserDel, false).eq(Order::getIsMerchantDel, false)
            );
        }

        long assembleCount = 0, fans = 0;
        if (!listed.isEmpty()) {
            fans = listed.size();
            assembleCount =
                    orderService.count(Wrappers.<Order>lambdaQuery().in(Order::getUid, listed.stream().map(EbUserRelationshipEntity::getUid).toList())
                            .in(Order::getStatus, 1, 5, 4, 6)
                            .eq(Order::getIsDel, false).eq(Order::getIsUserDel, false).eq(Order::getIsMerchantDel, false));
//                    orderService.count(Wrappers.<Order>lambdaQuery()
//                    .in(Order::getUid, listed.stream().map(EbUserRelationshipEntity::getUid).toList())
//                    .ge(Order::getCreateTime, DateUtil.beginOfDay(DateUtil.date(date)))
//                    .le(Order::getCreateTime, date)
//                    .eq(Order::getPlatOrderNo, "")
//                    .eq(Order::getStatus, 1)
//            );
            ;
        }
        BigDecimal voucherCount = userVoucherRecordService.getObjAs(userVoucherRecordService.from()
                .select(QueryMethods.sum(EbUserVoucherRecordEntity::getBalance))
                .where(EbUserVoucherRecordEntity::getUid).eq(info.getId())
                .eq(EbUserVoucherRecordEntity::getType, 1)
                .eq(EbUserVoucherRecordEntity::getStatus, 3)
                .orderBy(EbUserVoucherRecordEntity::getCreateTime).desc().limit(1), BigDecimal.class);
//        Object countGoldCoin = goldCoinRecordService.getObj(goldCoinRecordService.from()
//                .select(QueryMethods.sum(EbUserIntegralGoldCoinRecordEntity::getIntegral))
//                .where(EbUserIntegralGoldCoinRecordEntity::getUid).eq(info.getId()));
        // 金币取消
//        Object toDay = goldCoinRecordService.getObj(goldCoinRecordService.from()
//                .select(QueryMethods.sum(EbUserIntegralGoldCoinRecordEntity::getIntegral))
//                .ge(Order::getCreateTime, DateUtil.beginOfDay(DateUtil.date(date)))
//                .le(Order::getCreateTime, date).eq(Order::getUid, info.getId()));

        return R.success(Dict.of().set("assembleCount", assembleCount).set("todayCount", todayCount)
                .set("voucherCount", voucherCount)
//                .set("countGoldCoin", null).set("toDayGoldCoin", null)
                .set("fansCount", fans)
                .set("toDayFansCount", toDayFansCount));
    }

    /**
     * 添加 用户商品所获积分记录表
     *
     * @param ebUserIntegralProductRecord 用户商品所获积分记录表
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    public boolean save(@RequestBody EbUserIntegralProductRecordEntity ebUserIntegralProductRecord) {
        return ebUserIntegralProductRecordService.save(ebUserIntegralProductRecord);
    }


    /**
     * 根据主键删除用户商品所获积分记录表
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("/remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return ebUserIntegralProductRecordService.removeById(id);
    }


    /**
     * 根据主键更新用户商品所获积分记录表
     *
     * @param ebUserIntegralProductRecord 用户商品所获积分记录表
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("/update")
    public boolean update(@RequestBody EbUserIntegralProductRecordEntity ebUserIntegralProductRecord) {
        return ebUserIntegralProductRecordService.updateById(ebUserIntegralProductRecord);
    }


    /**
     * 查询所有用户商品所获积分记录表
     *
     * @return 所有数据
     */
    @GetMapping("/list")
    public List<EbUserIntegralProductRecordEntity> list() {
        return ebUserIntegralProductRecordService.list();
    }


    /**
     * 根据用户商品所获积分记录表主键获取详细信息。
     *
     * @param id ebUserIntegralProductRecord主键
     * @return 用户商品所获积分记录表详情
     */
    @GetMapping("/getInfo/{id}")
    public EbUserIntegralProductRecordEntity getInfo(@PathVariable Serializable id) {
        return ebUserIntegralProductRecordService.getById(id);
    }


    /**
     * 分页查询用户商品所获积分记录表
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("/page")
    public R<PageInfo<EbUserIntegralProductRecordEntity>> page(Page<EbUserIntegralProductRecordEntity> page,
                                                               @RequestParam(value = "type", required = false) String type) {
        User info = userService.getInfo();
        AtomicReference<PageInfo<EbUserIntegralProductRecordEntity>> objectPageInfo = new AtomicReference<>();
        LogicDeleteManager.execWithoutLogicDelete(() -> {
            objectPageInfo.set(PageHelper.startPage((int) page.getPageNumber(), (int) page.getPageSize())
                    .doSelectPageInfo(() -> ebUserIntegralProductRecordService.list(ebUserIntegralProductRecordService.from()
                            .where(EbUserIntegralProductRecordEntity::getUid).eq(info.getId())
                            .in(EbUserIntegralProductRecordEntity::getType, StrUtil.split(type, ",", true, true), StrUtil.isNotBlank(type))
                            .orderBy(EbUserIntegralProductRecordEntity::getCreateTime).desc())));
        });
        return R.success(objectPageInfo.get());
//        return ebUserIntegralProductRecordService.page(page);
    }
}